# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from .models import Log, User, Project, Branch
import re
import os
import subprocess
import datetime

user_static_dict = {}

def run(project, date_from, date_to, search_key):
    # try:
        os.chdir(project.dict)
        branches_list = get_branches()
        for branch_name in branches_list:
            branch, created = Branch.objects.get_or_create(branch_name=branch_name, project=project)
            deal_branch(date_from, date_to, branch, search_key)
    # except Exception, e:
    #     raise e


# get all branches of a project
def get_branches():
    branch_list = []
    try:
        cmd_git_remote = 'git remote show origin'
        proc = subprocess.Popen(cmd_git_remote.split(),
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        origin = stdout.split("URL:")[1].split("\n")[0]
        pn_list = origin.split("/")
        project_name = (pn_list[-1].split("."))[0]
        # save_project(origin, project_name)
        tmp_str = stdout.split('Local branches configured')[0]
        try:
            tmp_str = tmp_str.split('Remote branches:\n')[1]
        except:
            tmp_str = tmp_str.split('Remote branch:\n')[1]
        branches = tmp_str.split('\n')
        for branch in branches[0:-1]:
            if re.search(' tracked', branch) is not None:
                branch = branch.replace('tracked', '').strip(' ')
                branch_list.append(branch)
    except Exception, error:
        if branch_list == []:
            print "Can not get any branch!"
    return branch_list


# abstract log of one branch
def deal_branch(date_from, date_to, branch, search_key):
    os.system('git checkout %s' % branch.branch_name)
    os.system('git pull ')
    cmd_git_log = ["git",
                   "log",
                   "--stat",
                   "--no-merges",
                   "-m",
                   "--after=%s" % date_from,
                   "--before=%s" % date_to]
    proc = subprocess.Popen(cmd_git_log,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    branch_dic = deal_lines(date_from, date_to, search_key, stdout, branch)
    # return branch_dic
    # os.system('git pull ')
    # os.system('git log ')


# 分析日志
def deal_lines(date_from, date_to, search_key, stdout, branch):
    srt = stdout.replace('commit ', 'cut commit ').strip()
    for line in srt.split('cut '):
        # try:
            dic = {}
            # 获取版本号
            if re.search('commit ', line) is not None:
                commit_id = line.split('commit ')[1].split('\n')[0]

                # global logids
                # if not logids:
                #     logids = [x['commit'] for x in Log.objects.all().values('commit')]
                #
                # if commit_id in logids:
                #     continue
                dic['commit'] = [commit_id]
            # 获取作者信息
            if re.search('Author: ', line) is not None:
                author = line.split('Author: ')[1].split('\n')[0]
                dic['author'] = [author]
                user_list = author.split(' ')
                username = user_list[0]
                email = user_list[1].split('<')[1].split('>')[0].strip()
                if not user_static_dict.has_key(email):
                    user, created = User.objects.get_or_create(email=email)
                    if created:
                        print username
                    user.username = username
                    user.save()
                    user_static_dict[email] = user
                else:
                    user = user_static_dict[email]
            # 获取日期信息
            if re.search('Date: ', line) is not None:
                date = line.split('Date:   ')[1].split(' +')[0]
                dic['date'] = [date]
            # 获取修改被文件数量信息
            if re.search('file', line) is not None:
                change_str = line.strip().split('\n\n')[-1]
                fc_string0 = change_str.split('\n')
                fc_string = fc_string0[-1]
                fc_num = fc_string.split(' ')[1].split('file')[0]
                dic['file_changed'] = [fc_num]
            # 获取新增行数信息
            if re.search('insertion', line) is not None:
                insert_num = line.split('changed, ')[1].split('insertion')[0]
                dic['insertions'] = [insert_num]
            # 获取删除行数信息
            if re.search('deletion', line) is not None:
                delete_num = line.split('deletion')[0].split(',')[-1].strip()
                dic['deletions'] = [delete_num]
            if dic.get('commit'):
                save_log(dic, user, branch)
            else:
                continue
        # except Exception,error:
        #     print error
        #     raise error
    # return HttpResponse("success")


logids=[]
# 保存日志
def save_log(dic, user, branch):
    commit = ''.join(dic.get('commit', "not found"))
    global logids
    if not logids:
        logids = [x['commit'] for x in Log.objects.all().values('commit')]

    if commit in logids:
        pass
    else:
        a = Log()
        a.commit = commit
        a.author = user
        if dic.has_key('date'):
            date0 = ''.join(dic.get('date'))
            date = datetime.datetime.strptime(date0, "%a %b %d %H:%M:%S %Y")
        else:
            date = timezone.now()
        a.datetime = date
        a.files = int(''.join(dic.get('file_changed', "0")))
        a.add = int(''.join(dic.get('insertions', "0")))
        a.remove = int(''.join(dic.get('deletions', "0")))
        a.branch = branch
        a.save()


def start(request):
    # path of the .git project. example: "/home/username/projects/jekyll_vincent"

    date_from = "1970-01-01"
    date_to = datetime.datetime.now().strftime("%Y-%m-%d")
    # only search 'Bug: \d+' for default
    search_key = ""

    project_list = Project.objects.all()
    for project in project_list:
        run(project, date_from, date_to, search_key)
    return HttpResponse("success")


def save_project(request):
    """
    创建项目
    :param request:
    :return:
    """
    # 保存项目
    pro = Project()
    pro.dict = request.POST.get("dict")
    pro.pro_name = request.POST.get("name")
    pro.note = request.POST.get("note")
    pro.save()
    return HttpResponse("success")


def jump(request):
    return render(request, 'gitproject/create.html', )
